package com.qf.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qf.constant.MessageConstant;
import com.qf.constant.PasswordConstant;
import com.qf.constant.StatusConstant;
import com.qf.context.BaseContext;
import com.qf.exception.PasswordErrorException;
import com.qf.pojo.dto.PageUserQueryDTO;
import com.qf.pojo.dto.UserDTO;
import com.qf.pojo.dto.UserLoginDTO;
import com.qf.pojo.entity.User;
import com.qf.exception.AccountLockedException;
import com.qf.exception.AccountNotFoundException;
import com.qf.mapper.UserMapper;
import com.qf.pojo.vo.PageUserQueryVO;
import com.qf.pojo.vo.UserLoginVO;
import com.qf.pojo.vo.UserVO;
import com.qf.result.PageResult;
import com.qf.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    /**
     * 登录
     *
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.getUser(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对前端传过来的明文密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (user.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return user;
    }

    /**
     * 注册
     */
    @Override
    public void register(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);

        //判断用户是否存在
        User testUser = userMapper.getUser(userDTO.getUsername());
        if (testUser != null) {
            //存在相同用户名的用户,注册失败
            throw new RuntimeException(MessageConstant.ALREADY_EXISTS);
        }
        if(userDTO.getPassword() == null || userDTO.getPassword().isEmpty()) {
            BaseContext.setCurrentId(1L);
            //如果用户没有设置密码,则设置默认密码
            user.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        } else {
            //如果用户设置了密码,则对密码进行md5加密处理
            user.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        }
        user.setStatus(StatusConstant.ENABLE);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());


        //注册
        userMapper.register(user);
    }

    /**
     * 根据id查询用户信息
     */
    @Override
    public UserVO getUserById(Long id) {
        User user = userMapper.getUserById(id);
        if (user == null) {
            //用户不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码解密
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 分页查询用户列表
     */
    @Override
    public PageResult pageQuery(PageUserQueryDTO queryDTO) {
        // select * from employee limit 0,10
        //开始分页查询
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());

        //执行查询
        Page<User> page = userMapper.pageQuery(queryDTO);

        //获取分页查询结果
        long total = page.getTotal();
        List<User> records = page.getResult();
        return new PageResult(total, records);
    }


    /**
     * 根据id删除用户
     */
    @Override
    public void deleteUser(Long id) {
        List<Long> ids = new ArrayList<>();
        ids.add(id);
        userMapper.deleteUser(ids);
    }


    /**
     * 更新用户状态
     * @param status
     * @param id
     */
    @Override
    public void UpdateUserStatus(Integer status, Long id) {

        User user = User.builder()
            .status(status)
            .id(id)
            .updateTime(LocalDateTime.now())
            .build();

        userMapper.UpdateById(user);
    }


     /**
     * 根据id批量删除用户
     * @param ids
     */
    @Override
    public void deleteUsers(List<Long> ids) {
        userMapper.deleteUser(ids);
    }



    @Override
    public void updateById(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.UpdateById(user);
    }

}
